package cn.lgs.com.mobileplayer.base;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

import com.zhy.autolayout.AutoLayoutActivity;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AutoLayoutActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        init();
    }

    protected abstract void init();

  /*  public AppComponent getAppComponent() {
        return ((BaseApp) getApplication()).getAppComponent();
    }*/

    protected abstract int getContentViewId();

    public final Fragment findFragment(Class<? extends Fragment> paramClass) {
        return getSupportFragmentManager().findFragmentByTag(paramClass.getName());
    }

    public final Fragment findFragment(String classNameTag) {
        return getSupportFragmentManager().findFragmentByTag(classNameTag);
    }

    public final Fragment findFragment(int redId) {
        return getSupportFragmentManager().findFragmentById(redId);
    }

    public final void putFragment(int containerViewId, Fragment fragment, boolean replace) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        String str = fragment.getClass().getName();
        if (replace) {
            ft.replace(containerViewId, fragment, str);
        } else {
            ft.add(containerViewId, fragment, str);
        }
        ft.commitAllowingStateLoss();
    }

    public final void pushFragment(int containerViewId, Fragment fragment, boolean isReplace) {
        String str = fragment.getClass().getName();
        FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (isReplace) {
            localFragmentTransaction.replace(containerViewId, fragment, str);
        } else {
            localFragmentTransaction.add(containerViewId, fragment, str);
        }
        localFragmentTransaction.addToBackStack(str);
        localFragmentTransaction.commit();
    }

    /**
     * 吐司提示
     *
     * @param msg 信息字段
     */
    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected Fragment mCurrentFragment;

    /**
     * @param from 当前显示的Fragment, 即将被隐藏
     * @param to   将要切换到的Fragment，即将要显示
     */
    protected void changeFragment(Fragment from, Fragment to, int containerViewId) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (from == to || to == null) {
            return;
        }
        mCurrentFragment = to;
        if (null != from) {
            ft.hide(from);
        }
        if (to.isAdded()) {
            ft.show(to).commit();
        } else {
            ft.add(containerViewId, to).commit();
        }
    }

}
